package com.zg.nacos.service.impl;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.sun.corba.se.impl.naming.pcosnaming.NameServer;
import com.zg.common.core.R;
import com.zg.nacos.domain.bo.InstanceInfo;
import com.zg.nacos.domain.entity.MicroNacos;
import com.zg.nacos.domain.req.RegisterReq;
import com.zg.nacos.manager.InstanceManager;
import com.zg.nacos.manager.NamingServiceManager;
import com.zg.nacos.service.NacosService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/27 11:41
 */
@Service
@Slf4j
public class NacosServiceImpl implements NacosService {

    @Autowired
    private NamingServiceManager namingServiceManager;

    @Autowired
    private InstanceManager instanceManager;

    public boolean register(MicroNacos microNacos) {
        try {
            String namespace = microNacos.getNamespace();

            NamingService namingService = namingServiceManager.getNamingService(namespace);


            Instance instance = new Instance();
            instance.setIp(microNacos.getIp());
            instance.setPort(microNacos.getPort());
            instance.setServiceName(microNacos.getServiceName());
            String healthCheckUrl = microNacos.getHealthCheckUrl();
            if(!healthCheckUrl.startsWith("/")){
                healthCheckUrl="/"+healthCheckUrl;
            }
            Map<String, String> metadata = new HashMap<>();
            metadata.put("healthCheckUrl", "http://" + microNacos.getIp() + ":" + microNacos.getPort() + healthCheckUrl);
            instance.setMetadata(metadata);
            instance.setHealthy(false);
            namingService.registerInstance(microNacos.getServiceCode(), instance);
            //if (microNacos.()) {
                InstanceInfo instanceInfo = new InstanceInfo();
                BeanUtils.copyProperties(microNacos, instanceInfo);
                instanceManager.addInstance(instanceInfo);
            //}

            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }
}
